import { _decorator, Component, Sprite, Label, Color, Node, EventTouch, EventMouse } from 'cc';
const { ccclass, property } = _decorator;

import bezier_data from "./bezier_data";
import bezier_line from "./bezier_line";
export enum PointType {
    PATH = 0,
    CTRL = 1,
}

@ccclass('BezierPoint')
export default class bezier_point extends Component {
    @property(Sprite)
    private bg: Sprite | null = null;
    @property(Label)
    private index: Label | null = null;
    private _index: number = 0;
    private _pointType: PointType = PointType.PATH;
    private _bezierLine: bezier_line = null;
    public get pointType(): PointType { return this._pointType; }
    protected start() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.MOUSE_DOWN, this.onMouseDown, this);
    }
    public init(index: number, type: PointType, line: bezier_line) {
        this.updateIndex(index);
        this._pointType = type;
        this._bezierLine = line;
        this.bg.color = type === PointType.PATH ? Color.GREEN : Color.RED;
    }
    public updateIndex(index: number) {
        this._index = index;
        this.index.string = `${index}`;
    }
    private onTouchStart(event: EventTouch) {
        this._bezierLine.node.emit('pointSelect');
        event.propagationStopped = true;
    }
    private onTouchMove(event: EventTouch) {
        const delta = event.getDelta();
        if (bezier_data.shiftPressed) {
            this._bezierLine.node.emit('lineMove', delta);
            console.log('lineMove')
        } else {
            this.node.x += delta.x;
            this.node.y += delta.y;
            this._bezierLine.node.emit('pointMove', this._index, delta);
        }
        event.propagationStopped = true;
    }
    private onMouseDown(event: EventMouse) {
        const mouseButton = event.getButton();
        if (mouseButton === EventMouse.BUTTON_RIGHT) {
            if (bezier_data.shiftPressed) {
                // shift + RMB = 删除节点(仅限路径点)
                if (this._pointType === PointType.PATH) this._bezierLine.node.emit('pointDel', this._index);
            } else {
                // RMB = 增加节点
                this._bezierLine.node.emit('pointAdd');
            }
        }
        event.propagationStopped = true;
    }
}
